package cn.waka.sys.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.Result;
import cn.waka.sys.admin.object.User;
import cn.waka.sys.admin.service.UserService;

@RestController
public class LoginController extends BaseController {

	private UserService userService;

	@RequestMapping(path = "/login", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
	public ModelAndView index(HttpServletRequest req, HttpServletResponse res) {

		return new ModelAndView("/login/index");
	}


	@RequestMapping(path = "/check", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
	public Result submit(HttpServletRequest req, HttpServletResponse res) {
		String username = req.getParameter("uname");
		String password = req.getParameter("password");
		if (username == null || password == null || username.length() == 0 || password.length() == 0) {
			return error(-101, "请输入用户名或密码!");
		}
		User u = userService.checkUser(username, password);
		if (u == null) {
			return error(-102, "登录密码与账号不匹配，请重新输入!");
		} else {
			HttpSession sess = req.getSession();
			sess.setAttribute("uid", u.getId());
			sess.setAttribute("uname", u.getUsername());
			sess.setAttribute("roles", u.getAuthorize());
			sess.setAttribute("authorize", u.getAuthorize());
		}
		Result rs = ok();
		rs.setUrl("main");
		rs.setMsg("登录成功!");
		res.setHeader("Pragma", "No-cache");
		res.setHeader("Cache-Control", "no-cache");
		res.setDateHeader("Expires", 0);
		return rs;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
